import 'dart:async';
import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/entity/shop_car_entity.dart';
import 'package:panda/event/LoginEvent.dart';
import 'package:panda/event/ShopCarEvent.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/login/Welcome.dart';
import 'package:panda/order/OrderPage.dart';
import 'package:panda/order/OrderPay.dart';
import 'package:panda/set/FillAuthCode.dart';
import 'package:panda/set/VIPTest.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/DateUtils.dart';
import 'package:panda/util/SignUtil.dart';
import 'package:panda/goods/BuyGoodsByCar.dart';

class MyShopCarPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyShopCarFragmentState();
  }
}

class MyShopCarFragmentState extends State<MyShopCarPage>
    with WidgetsBindingObserver {
  final SlidableController slidableController = SlidableController();
  Timer _timerIndex;

  EasyRefreshController _controller = new EasyRefreshController();
  int currentStatus = 0;
  bool isSelectAll = false;
  double total = 0;
  String token = "";
  List<MyShopCarDataData> dataList = new List();
  List<MyShopCarDataData> dataList2 = new List();

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      if (!ModalRoute.of(context).isCurrent) {
        return;
      }
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    const period = const Duration(seconds: 1);
    _timerIndex = Timer.periodic(period, (timer) {
      setState(() {});
      // debugPrint(_text);
    });
    getString(TOKEN).then((value) {
      token = value;
      if (token == null) {
        return;
      }
      loadList();
    });
    APPLIC.eventBus.on<ShopCarEvent>().listen((event) {
      loadList();
    });
    APPLIC.eventBus.on<LoginEvent>().listen((event) {
      getString(TOKEN).then((value) {
        token = value;
        if (token == null) {
          return;
        }
        loadList();
      });
    });
  }

  @override
  void dispose() {
    _timerIndex.cancel();
    _timerIndex = null;
    WidgetsBinding.instance.removeObserver(this); //销毁观察者

    super.dispose();
  }

  loadList() async {
    if (token == null) {
      return;
    }
    Map map = new Map();
    map['token'] = token;
    map['p'] = "1";
    map['per'] = "100";
    map['sign_type'] = SignType.GET_SHOP_CAR;
    Response<String> response =
        await HttpUtil().post(Api.GET_SHOP_CAR, data: getSign(map));
    Map userMap = json.decode(response.data);
    // if (mounted) if (page == 1) {
    //   _controller.finishRefresh();
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    MyShopCarEntity homeListEntity = new MyShopCarEntity.fromJson(userMap);
    if (mounted) total = 0;
    isSelectAll = false;
    setState(() {
      dataList.clear();
      dataList2.clear();
      _controller.finishRefresh();
      dataList.addAll(homeListEntity.data.datas);
      dataList2.addAll(homeListEntity.data.datas2);
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(
          "购物车",
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
              color: Colors.black),
        ),
        elevation: 0.5,
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        // actions: <Widget>[
        //   GestureDetector(
        //     child: Container(
        //       alignment: Alignment.center,
        //       padding: EdgeInsets.fromLTRB(0, 0, 13, 0),
        //       child: Text(
        //         currentStatus == 0 ? '编辑' : '完成',
        //         style: TextStyle(
        //             fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
        //             color: Colors.black54),
        //       ),
        //     ),
        //     onTap: () {
        //       if (currentStatus == 0) {
        //         currentStatus = 1;
        //         setState(() {});
        //       } else {
        //         currentStatus = 0;
        //         setState(() {});
        //       }
        //     },
        //   )
        // ],
      ),
      body: AnnotatedRegion<SystemUiOverlayStyle>(
        child: Column(
          children: <Widget>[
            Expanded(
              child: new EasyRefresh(
                controller: _controller,
                header: MaterialHeader(),
                footer: MaterialFooter(),
                enableControlFinishLoad: false,
                enableControlFinishRefresh: true,
                child: ListView.builder(
                  itemCount: dataList.length + dataList2.length,
                  itemBuilder: (BuildContext context, int index) {
                    if (index >= dataList.length)
                      return renderView2(context, index);
                    return renderView(context, index);
                  },
                ),
                onRefresh: () {
                  currentStatus = 0;
                  isSelectAll = false;
                  loadList();
                },
              ),
            ),
            Container(
              height: 0.5,
              color: f0Color,
            ),
            Container(
              color: white,
              padding: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(5),
                  ScreenUtil.getInstance().setHeight(DP_10),
                  ScreenUtil.getInstance().setHeight(40),
                  ScreenUtil.getInstance().setHeight(DP_10)),
              child: Row(
                children: <Widget>[
                  Checkbox(
                      value: isSelectAll,
                      activeColor: mainColor,
                      checkColor: white,
                      materialTapTargetSize: MaterialTapTargetSize.padded,
                      onChanged: (bool x) {
                        isSelectAll = !isSelectAll;
                        checkAll();
                        setState(() {});
                      }),
                  Text('全选',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                          color: Colors.black87)),
                  Expanded(
                    child: Text(''),
                  ),
                  Text(currentStatus == 0 ? '合计：' : '',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black87)),
                  Text(currentStatus == 0 ? (MONEY + '$total') : '',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                          color: Colors.red)),
                  Expanded(
                    child: Text(''),
                  ),
                  new Container(
                    height: ScreenUtil.getInstance().setHeight(DP_50),
                    decoration: new BoxDecoration(
                        color: mainColor,
                        borderRadius: BorderRadius.circular(4.0)),
                    padding: EdgeInsets.fromLTRB(5.0, 0.0, 5.0, 0.0),
                    child: new FlatButton(
                      child: new Padding(
                        padding: EdgeInsets.all(0.0),
                        child: new Text(
                          currentStatus == 0 ? "去结算" : '删除',
                          style: new TextStyle(
                              color: Colors.white,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE)),
                        ),
                      ),
                      onPressed: () {
                        if (APPLIC.userInfoMap == null) {
                          Navigator.of(context)
                              .push(new MaterialPageRoute(builder: (context) {
                            return new WelComePage();
                          }));
                          return;
                        }
                        // if (APPLIC.userInfoMap['user_msg']['group_id']
                        //         .toString() ==
                        //     "1") {
                        //   Navigator.of(context)
                        //       .push(new MaterialPageRoute(builder: (context) {
                        //     return new VIPTestPage();
                        //   }));
                        //   return;
                        // }
                        if (currentStatus == 0) {
                          List<MyShopCarDataData> temp = new List();
                          for (int i = 0; i < dataList.length; i++) {
                            if (dataList[i].isSelect) {
                              temp.add(dataList[i]);
                            }
                          }
                          Navigator.of(context)
                              .push<Map>(MaterialPageRoute(builder: (context) {
                            return new BuyGoodsByCarPage(
                              datas: temp,
                              total: total.toString(),
                            );
                          })).then((value) {
                            if (value != null) {
                              loadList();
                              Navigator.of(context).push<String>(
                                  MaterialPageRoute(builder: (context) {
                                return new OrderPayPage(
                                    orderId: value['data']['order_id'],
                                    title: value['data']['title'],
                                    orderNum: value['data']['order_num'],
                                    create_time:value['data']['create_time'],
                                    totalMoney:
                                        value['data']['allprice'].toString());
                              })).then((value) {
                                // if (value != null) {
                                  currentStatus = 0;
                                  isSelectAll = false;
                                  loadList();
                                  Navigator.of(context).push(
                                      MaterialPageRoute(builder: (context) {
                                    return new OrderPage();
                                  }));
                                // }
                              });
                            }
                          });
                        }
                      },
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
        value: SystemUiOverlayStyle.dark,
      ),
    );
  }

  Widget renderView2(BuildContext context, int index) {
    bool isShow = true;
    if (index == dataList.length) {
      isShow = false;
    }
    index = index - dataList.length;
    return Column(
      children: <Widget>[
        Offstage(
          offstage: isShow,
          child: Padding(
            padding: EdgeInsets.fromLTRB(10, 15, 10, 15),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Text('以下商品已失效',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black87)),
                ),
                GestureDetector(
                  child: Text('清理失效商品',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: mainColor)),
                  onTap: () {
                    del2();
                  },
                  behavior: HitTestBehavior.opaque,
                ),
              ],
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.fromLTRB(
              ScreenUtil.getInstance().setHeight(DP_15),
              ScreenUtil.getInstance().setHeight(0),
              ScreenUtil.getInstance().setHeight(DP_15),
              0),
          decoration: BoxDecoration(
              color: white,
              borderRadius: BorderRadius.circular(
                  ScreenUtil.getInstance().setHeight(DP_10))),
          child: Padding(
            padding: EdgeInsets.fromLTRB(
                ScreenUtil.getInstance().setHeight(20),
                ScreenUtil.getInstance().setHeight(DP_20),
                ScreenUtil.getInstance().setHeight(DP_20),
                ScreenUtil.getInstance().setHeight(DP_20)),
            child: new Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Expanded(
                    child: Column(
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Stack(
                          children: <Widget>[
                            ClipRRect(
                              borderRadius: BorderRadius.circular(5),
                              child: CachedNetworkImage(
                                  imageUrl:
                                      Api.ImgBaseUrl + dataList2[index].img,
                                  width: ScreenUtil.getInstance()
                                      .setHeight(DP_120),
                                  fit: BoxFit.fill,
                                  height: ScreenUtil.getInstance()
                                      .setHeight(DP_120)),
                            ),
                            Positioned(
                                bottom: 0,
                                child: Container(
                                  width: ScreenUtil.getInstance()
                                      .setHeight(DP_120),
                                  color: Color(0x55000000),
                                  alignment: Alignment.center,
                                  child: Text("已下架",
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(NORMAL_FONT_SIZE - 5),
                                          color: Colors.white)),
                                ))
                          ],
                        ),
                        Container(
                          width: ScreenUtil.getInstance().setHeight(DP_15),
                        ),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(dataList2[index].goods_name,
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE),
                                      color: Colors.black45)),
                              Container(
                                height:
                                    ScreenUtil.getInstance().setHeight(DP_10),
                              ),
                              Text(dataList2[index].sku_str,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(MINI_FONT_SIZE),
                                      color: Colors.black38)),
                              Container(
                                height:
                                    ScreenUtil.getInstance().setHeight(DP_10),
                              ),
                              Row(
                                children: <Widget>[
                                  Expanded(
                                    child: Text(MONEY + dataList2[index].price,
                                        maxLines: 1,
                                        style: TextStyle(
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(BIG_FONT_SIZE),
                                            color: Colors.black)),
                                  ),
                                ],
                              )
                            ],
                          ),
                        )
                      ],
                    )
                  ],
                ))
              ],
            ),
          ),
        )
      ],
    );
  }

  Widget renderView(BuildContext context, int index) {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil.getInstance().setHeight(DP_15),
          ScreenUtil.getInstance().setHeight(DP_15),
          ScreenUtil.getInstance().setHeight(DP_15),
          0),
      decoration: BoxDecoration(
          color: white,
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_10))),
      child: Slidable(
        actionPane: SlidableStrechActionPane(),
        controller: slidableController,
        actionExtentRatio: 0.25,
        secondaryActions: <Widget>[
          IconSlideAction(
            caption: '删除',
            color: mainColor,
            icon: Icons.delete,
            closeOnTap: true,
            onTap: () {
              del(index);
            },
          ),
        ],
        child: Padding(
          padding: EdgeInsets.fromLTRB(
              ScreenUtil.getInstance().setHeight(0),
              ScreenUtil.getInstance().setHeight(DP_20),
              ScreenUtil.getInstance().setHeight(DP_20),
              ScreenUtil.getInstance().setHeight(DP_20)),
          child: new Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Checkbox(
                  value: dataList[index].isSelect,
                  activeColor: mainColor,
                  checkColor: white,
                  materialTapTargetSize: MaterialTapTargetSize.padded,
                  onChanged: (bool x) {
                    dataList[index].isSelect = !dataList[index].isSelect;
                    change();
                    setState(() {});
                  }),
              Expanded(
                  child: Column(
                children: <Widget>[
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: <Widget>[
                      Text("距离活动仅剩余 ",
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE - 2),
                              color: Colors.black54)),
                      Text(DateUtils.timeFunc(dataList[index].end_time),
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE),
                              color: mainColor)),
                    ],
                  ),
                  Container(
                    height: 7,
                  ),
                  Row(
                    children: <Widget>[
                      ClipRRect(
                        borderRadius: BorderRadius.circular(5),
                        child: CachedNetworkImage(
                            imageUrl: Api.ImgBaseUrl + dataList[index].img,
                            width: ScreenUtil.getInstance().setHeight(DP_120),
                            fit: BoxFit.fill,
                            height: ScreenUtil.getInstance().setHeight(DP_120)),
                      ),
                      Container(
                        width: ScreenUtil.getInstance().setHeight(DP_15),
                      ),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(dataList[index].goods_name,
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(NORMAL_FONT_SIZE),
                                    color: Colors.black87)),
                            Container(
                              height: ScreenUtil.getInstance().setHeight(DP_10),
                            ),
                            Text(dataList[index].sku_str,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(MINI_FONT_SIZE),
                                    color: Colors.black38)),
                            Container(
                              height: ScreenUtil.getInstance().setHeight(DP_10),
                            ),
                            Row(
                              children: <Widget>[
                                Expanded(
                                  child: Text(MONEY + dataList[index].price,
                                      maxLines: 1,
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(BIG_FONT_SIZE),
                                          color: black)),
                                ),
                                GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    if (dataList[index].goods_num == "1") {
                                      return;
                                    }
                                    dataList[index].goods_num =
                                        (int.parse(dataList[index].goods_num) -
                                                1)
                                            .toString();
                                    change();
                                    setState(() {});
                                  },
                                  child: Icon(
                                    Icons.remove,
                                    size: ScreenUtil.getInstance()
                                        .setHeight(DP_30),
                                    color: black,
                                  ),
                                ),
                                Container(
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(2),
                                      color: f0Color),
                                  padding: EdgeInsets.fromLTRB(
                                      ScreenUtil.getInstance().setHeight(DP_20),
                                      2,
                                      ScreenUtil.getInstance().setHeight(DP_20),
                                      2),
                                  margin: EdgeInsets.fromLTRB(
                                      ScreenUtil.getInstance().setHeight(DP_10),
                                      0,
                                      ScreenUtil.getInstance().setHeight(DP_10),
                                      0),
                                  child: Text(
                                    dataList[index].goods_num,
                                    style: TextStyle(
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(SMALL_FONT_SIZE),
                                        color: Colors.black87),
                                  ),
                                ),
                                GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    dataList[index].goods_num =
                                        (int.parse(dataList[index].goods_num) +
                                                1)
                                            .toString();
                                    change();
                                    setState(() {});
                                  },
                                  child: Icon(
                                    Icons.add,
                                    size: ScreenUtil.getInstance()
                                        .setHeight(DP_30),
                                    color: black,
                                  ),
                                ),
                              ],
                            )
                          ],
                        ),
                      )
                    ],
                  )
                ],
              ))
            ],
          ),
        ),
      ),
    );
  }

  del(int pos) async {
    Map map = new Map();
    map['token'] = token;
    map['id'] = dataList[pos].id;
    map['sign_type'] = SignType.DEL_FROM_CAR;
    Response<String> response =
        await HttpUtil().post(Api.DEL_FROM_CAR, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap['code'];
    if (code == 1) {
      dataList.removeAt(pos);
      change();
      setState(() {});
    } else {
      Fluttertoast.showToast(msg: userMap['msg']);
      userMap = null;
    }
  }

  del2() async {
    String id = "";
    for (int i = 0; i < dataList2.length; i++) {
      id += dataList2[i].id + ",";
    }
    Map map = new Map();
    map['token'] = token;
    map['id'] = id.substring(0, id.length - 1);
    map['sign_type'] = SignType.DEL_FROM_CAR;
    Response<String> response =
        await HttpUtil().post(Api.DEL_FROM_CAR, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap['code'];
    Fluttertoast.showToast(msg: userMap['msg']);
    if (code == 1) {
      loadList();
    } else {
      userMap = null;
    }
  }

  change() {
    total = 0;
    for (int i = 0; i < dataList.length; i++) {
      if (dataList[i].isSelect) {
        total = total +
            int.parse(dataList[i].goods_num) * double.parse(dataList[i].price);
      }
    }
    total = double.parse(formatNum(total, 2));
  }

  String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      return num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    } else {
      return num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    }
  }

  checkAll() {
    for (int i = 0; i < dataList.length; i++) {
      dataList[i].isSelect = isSelectAll;
    }
    change();
    setState(() {});
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return false;
  }
}

class BuGoodsByCarPage {}
